var mongoose = require('mongoose')
var SALT_WORK_FACTOR = 10

var UserSchema = new mongoose.Schema({
  
  name: { 
  	type: String, 
  	required: true 
  },
  password: { 
  	type: String, 
  	required: true 
  },
  email:{
    type: String,
    require: false
  },
  tel:{
    type: Number,
    require: false
  },
  //0: 普通用户
  //1：管理员
  role: {
    type: Number,
    default: 0
  },
  meta: {
    createAt: {
      type: Date,
      default: Date.now()
    },
    updateAt: {
      type: Date,
      default: Date.now()
    }
  }
})

UserSchema.pre('save', function(next) {
  var user = this

  if (this.isNew) {
    this.meta.createAt = this.meta.updateAt = Date.now()
  }
  else {
    this.meta.updateAt = Date.now()
  }

  next()
})

UserSchema.statics = {
  fetch: function(cb) {
    return this
      .find({})
      .sort('meta.updateAt')
      .exec(cb)
  },
  findById: function(id, cb) {
    return this
      .findOne({_id: id})
      .exec(cb)
  }
}

module.exports = UserSchema